const smsModel = require('../models/smsModel');
const smsService = require('../utils/sms');
const { sendSuccess, sendError } = require('../utils/response');
const { generateRandomCode } = require('../utils/helpers');

module.exports = {
  // 发送验证码
  async sendVerificationCode(req, res) {
    try {
      const { phone } = req.body;
      
      if (!phone) {
        return sendError(res, '手机号不能为空', 400);
      }
      
      // 生成6位随机验证码
      const code = generateRandomCode(6);
      
      // 保存验证码到数据库
      await smsModel.createVerificationCode(phone, code);
      
      // 发送短信
      const sent = await smsService.sendVerificationCode(phone, code);
      
      if (!sent) {
        return sendError(res, '短信发送失败', 500);
      }
      
      sendSuccess(res, code, '验证码已发送');
    } catch (err) {
      sendError(res, err.message);
    }
  },

  // 验证验证码
  async verifyCode(req, res) {
    try {
      const { phone, code } = req.body;
      
      if (!phone || !code) {
        return sendError(res, '手机号和验证码不能为空', 400);
      }
      
      const isValid = await smsModel.verifyCode(phone, code);
      
      if (!isValid) {
        return sendError(res, '验证码无效或已过期', 400);
      }
      
      sendSuccess(res, { verified: true }, '验证码验证成功');
    } catch (err) {
      sendError(res, err.message);
    }
  }
};